package com.tmall.tmall.controller;

import com.tmall.tmall.pojo.Result;
import com.tmall.tmall.pojo.User;
import com.tmall.tmall.pojo.UserLogin;
import com.tmall.tmall.pojo.UserLoginRt;
import com.tmall.tmall.service.UserService;
import com.tmall.tmall.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录和注册
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class LoginAndRegisteredController {
    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param userLogin
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserLogin userLogin) throws NoSuchAlgorithmException {
        User user = userService.login(userLogin);
        if(user!=null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",user.getId());
            claims.put("name",user.getName());
            claims.put("type",user.getType());
            claims.put("password",user.getPassword());
            String jwt = JwtUtils.generateJwt(claims);
            UserLoginRt userLoginRt = UserLoginRt.builder().jwt(jwt).type(user.getType()).build();
            return Result.success(userLoginRt);
        }
        return Result.error("用户名或密码错误");
    }

    /**
     * 注册
     * @param userLogin
     * @return
     */
    @PutMapping("/register")
    public Result registered(@RequestBody UserLogin userLogin) throws NoSuchAlgorithmException {
        User user = userService.getByName(userLogin);
        if(user!=null){
            return Result.error("用户名重复");
        }
        userLogin.setType("user");
        userService.insert(userLogin);
        return Result.success();
    }
}
